package com.school.basic.service.impl;

import com.school.basic.entity.AreaInfo;
import com.school.basic.entity.SchoolInfo;
import com.school.basic.entity.TeacherInfo;
import com.school.basic.repository.AreaInfoRepository;
import com.school.basic.repository.SchoolInfoRepository;
import com.school.basic.service.SchoolInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class SchoolInfoInfoServiceImp implements SchoolInfoService {
    @Autowired
    SchoolInfoRepository schoolInfoRepository;
    @Autowired
    AreaInfoRepository areaInfoRepository;

    /**
     * 增加
     * @param schoolInfo
     * @return
     */
    @Override
    public SchoolInfo addSchoolInfo(SchoolInfo schoolInfo) {
        schoolInfo.setCreateDate(new Date());
        schoolInfo.setUpdateDate(new Date());
        return schoolInfoRepository.saveAndFlush(schoolInfo);
    }

    /**
     * 修改
     * @param schoolInfo
     * @return
     */
    @Override
    public SchoolInfo updateSchoolInfo(SchoolInfo schoolInfo) {
        schoolInfo.setUpdateDate(new Date());
        return schoolInfoRepository.saveAndFlush(schoolInfo);
    }

    /**
     * 查看详情
     * @param id
     */
    @Override
    public SchoolInfo getDetailsById(String id) {
        return schoolInfoRepository.findById(Integer.valueOf(id)).get();
    }

    /**
     * 学校信息状态变更
     * @param id,status
     */
    @Override
    public void updateStatus(String id,Integer status) {
        SchoolInfo schoolInfo;
        try {
            schoolInfo = schoolInfoRepository.findById(Integer.valueOf(id)).get();
            schoolInfo.setStatus(status);
            schoolInfoRepository.saveAndFlush(schoolInfo);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void deleteSchoolInfo(String id) {
        SchoolInfo schoolInfo;
        try {
            schoolInfo = schoolInfoRepository.findById(Integer.valueOf(id)).get();
            schoolInfoRepository.delete(schoolInfo);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量删除
     * @param idList
     */
    @Override
    public void deleteSchoolInfoList(String idList) {
        String[] split = idList.split(",");
        List<Integer> list = new ArrayList<>();
        for (String s : split) {
            list.add(Integer.parseInt(s));
        }
        schoolInfoRepository.deleteSchoolsByIdIn(list);
    }

    /**
     * 根据条件分页查询
     * @param schoolInfo,page,size
     */
    @Override
    public Page<SchoolInfo> specificPageQuerySchoolInfoList(SchoolInfo schoolInfo, int page, int size) {
        Specification querySpecification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if(schoolInfo != null)
                {
                    Integer status = schoolInfo.getStatus();
                    String schoolName = schoolInfo.getSchoolName();
                    if (status != null)
                    {
                        predicates.add(criteriaBuilder.equal(root.get("status").as(Integer.class),status));
                    }
                    if (!StringUtils.isEmpty(schoolName))
                    {
                        predicates.add(criteriaBuilder.like(root.get("schoolName").as(String.class),'%' + schoolName + '%'));
                    }
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        List<SchoolInfo> schoolInfoList = schoolInfoRepository.findAll(querySpecification);
        for(int i = 0; i < schoolInfoList.size(); i ++){
            Integer areaInfoId = schoolInfoList.get(i).getAreaInfoId();
            if(areaInfoId != null){
                AreaInfo areaInfo = areaInfoRepository.findById(areaInfoId).get();
                if(areaInfo != null){
                    schoolInfoList.get(i).setName(areaInfo.getName());
                }
            }
        }
        PageRequest pageRequest = PageRequest.of(page-1, size, Sort.by(Sort.Direction.DESC,"updateDate"));
        // 当前页第一条数据在List中的位置
        int start = (int)pageRequest.getOffset();
        // 当前页最后一条数据在List中的位置
        int end = (start + pageRequest.getPageSize()) > schoolInfoList.size() ? schoolInfoList.size() : ( start + pageRequest.getPageSize());
        // 配置分页数据
        return new PageImpl<SchoolInfo>(schoolInfoList.subList(start, end), pageRequest, schoolInfoList.size());
    }

    /**
     * 查询所有
     * @param
     */
    @Override
    public List<SchoolInfo> findAll() {
        return schoolInfoRepository.findAll();
    }

    @Override
    public SchoolInfo findSchoolByAccountAndPassword(String account, String password) {
        SchoolInfo schoolInfo = new SchoolInfo();
        schoolInfo.setAccount(account);
        schoolInfo.setPassword(password);
        Optional<SchoolInfo> one = schoolInfoRepository.findOne(Example.of(schoolInfo));
        schoolInfo = null;
        return one.orElse(null);
    }
}
